<?

include_once('config.php');
function show_category($dopinfo,$type) {

    $z = mysql_query("select id,title from cat where inexcel=1 and ( parent is null or parent=0) order by id") or die(mysql_error());
    $cnt = mysql_num_rows($z);
    $i = 1;
    $two = ceil(($cnt/2)+7);
    while ($t = mysql_fetch_assoc($z)) {
        if ($i == 1) $text .= '<div style="width: 45%; float: left; ">';
           if ($i == $two) $text .= '</div><div style="width: 45%; float: right; ">';
        $text .= '<b><h2><a href="/catalog/group/'.$t['id'].'">'.$t['title'].'</a></h2></b>';        
        $parent = $t['id'];
        $sq = mysql_query("select id,title from cat where inexcel=1 and parent = '$parent'");
        if (mysql_num_rows($sq) != 0) 
            while ($tt = mysql_fetch_assoc($sq)) {
                $text .= '<a class="sub_group" href="/catalog/group/'.$tt['id'].'/">'.$tt['title'].'</a><br />';
                
            }
            $i++;
    }
    $text .= '</div>';
    return $text;
}
function showItemByCat($idgroup,$main_group, $subCat=false, $itemLimit=10){
                    $defOnPage=$itemLimit;
                    $onPage=empty($_GET['OnPage'])?$defOnPage:$_GET['OnPage'];
                    $Page = empty($_GET['page'])?1:$_GET['page'];
                    if (!$subCat){
                        $c=mysql_query('select count(id) as c from catalog where cat='.$idgroup.' and inexcel=1') or die(mysql_error());
                        $c=mysql_fetch_assoc($c);
                        $c=$c['c'];
                        $paginator='';
                        $limits='';
                        $orderby=' order by title';
                        if ($onPage!='all'){
                            $page_count=ceil($c/$onPage);
                            for ($i=1; $i<$page_count+1; $i++){
                                if ($onPage!=$defOnPage){
                                    $add_url='&OnPage='.$onPage;
                                }
                                if ($Page!=$i)
                                    $paginator.='<a href="?page='.$i.$add_url.'">'.$i.'</a>&nbsp;';
                                else
                                    $paginator.=$i.'&nbsp;';
                            }
                            $limits=' limit '.(($Page-1)*$onPage).','.$onPage;
                        }
                        $countOut='Выводить позиций: <a href="?OnPage=10">10</a>&nbsp;&nbsp;<a href="?OnPage=15">15</a>&nbsp;&nbsp;<a href="?OnPage=30">30</a>&nbsp;&nbsp;<a href="?OnPage=all">Все ('.$c.')</a>';
                    }else{
                        $orderby=' order by RAND()';    
                        $limits=' limit 0,'.$defOnPage;
                        $main_group['title']='<a href="/catalog/group/'.$main_group['id'].'">'.$main_group['title'].'</a>';
                        $paginator='';
                        $countOut='<a href="/catalog/group/'.$main_group['id'].'">Показать все</a>';
                    }
                    $items=  mysql_query('select * from catalog where inexcel=1 and cat='.$idgroup.$orderby.$limits) or die (mysql_error());
                    $item_out='';
                    if (mysql_affected_rows()<=0){
                        $item_out='Не найдено позиций';
                    }else{
                        $item_out.='<div class="item-out">';
                        $item_out.='<table width="100%">';
                        $item_out.='<tr><th width="150">арт.</th><th>наименование</th><th width="150">стоимость,р</th><th width="150">поместить в корзину</th></tr>';
                        
                        while ($item =  mysql_fetch_assoc($items)){
                            $item_out.='<tr><td class="gr_cell"><a href="/catalog/item/'.$item['id'].'">'.$item['art'].'</a></td><td><a href="/catalog/item/'.$item['id'].'">'.$item['title'].'</td><td><a href="/catalog/item/'.$item['id'].'">'.$item['price'].'</a></a></td><td class="gr_cell"><a class="addto-cart to-basket" href="/to_basket?item='.$item['id'].'" title="В корзину"><img src="/images/in_basket_small.png" /></td>'.  admin_message(10, '<td><a title="изменить" href="/ADM/edit/'.$item['id'].'?vid=catalog"><img src="/images/edit_256.png" width="20" /></a></td>').admin_message(10, '<td><a title="удалить" href="/ADM/delete/'.$item['id'].'?vid=catalog"><img src="/images/delete.png" width="20" /></a></td>').'</tr>';
                        }
                        $item_out.='</table>';
                        $item_out.='</div>';
                    }
                    ?>
                    <div class="catalog-head">
                        <table width="100%">
                            <tr>
                                <td width="350"><h1><?=$main_group['title']?></h1></td>
                                <td style="text-align: center;">
                                   <?=$paginator?>
                                </td>
                                <td width="270"><?=$countOut?></td>
                            </tr>
                        </table>
                        
                    </div>
                    <?=$item_out?>
                    <?
}
function catalog($target, $path) {    
    $text='';
    switch ($path[2]){
        case ('search'):
            include_once 'search.inc';
            $text.=search($target);
            break;
        case (''):
                if ($target == 'title')
                    $text.='Каталог';
                if ($target == 'content') {
                    $text.='<div style="text-align:left;">'.kroshki('catalog', array('/'=>'Главная','/catalog.html'=>'Каталог')).'</div>';
                    $text.=$dopinfo;
                    //$text.=;
                    $text.=show_category($dopinfo, "left-top"); 
                    $q=mysql_fetch_assoc(mysql_query('select * from pages where parent="/zapchasti" limit 0,1'));
                    $text.='<br />';
                    $text.=admin_message(9,'<a href="/ADM/edit/'.$q['id'].'/?vid=pages">Редактировать</a>');
                    $text.='<div>'.$q['content'].'</div>';
                }
            break;
        
        case ('group'):
            $idgroup=empty($path[3])?0:$path[3];
            $main_group=  mysql_fetch_assoc(mysql_query('select * from cat where  inexcel=1 and id='.$idgroup));
            if (!isset($main_group['id'])){
                echo TraceOut($target, 'Группа не найдена', 'Группа не найдена, попробуйте начать с <a href="/catalog/">начала</a>');
            }else{
                if ($target=='title'){
                    echo $main_group['title'].' | Каталог';
                }elseif($target=='content'){
                    echo '<div style="text-align:left;">'.kroshki('catalog', array('/'=>'Главная','/catalog.html'=>'Каталог','/catalog/group/'.$main_group['id']=>$main_group['title'])).'</div>';
                    $childCount=mysql_query('select count(id) as c from cat where inexcel=1 and parent='.$idgroup);
                    $childCount=mysql_fetch_assoc($childCount);
                    
                    if ($childCount['c']<=0){
                        showItemByCat($idgroup,$main_group);
                    }else{
                        $childs=mysql_query('select id,title from cat where inexcel=1 and parent='.$idgroup);
                        while ($ch=  mysql_fetch_assoc($childs)){
                            showItemByCat($ch['id'], $ch, true, 5);
                            echo '<br/>';
                        }
                        
                    }
                }
            }
            break;
            case 'item':
                $iditem=empty($path[3])?0:$path[3];
                $item_info=  mysql_fetch_assoc(mysql_query('select * from catalog where id='.$iditem));
                if (!isset($item_info['id'])){
                    echo TraceOut($target, 'Товар не найден', 'Товар не найден, попробуйте начать с <a href="/catalog/">начала</a>');
                }else{
                    if ($target=='title'){
                        echo $item_info['title'].' | Каталог';
                    }elseif ($target=='content'){
                        ob_start();
                        if ($_SESSION['level'] >= 5)
                           echo '<div ondblclick="parent.location=\'/ADM/edit/' . $item_info['id'] . '/?vid=catalog\'" title="Кликните дважды для редактирования">
                           <a href="/ADM/delete/'.$item_info['id'].'/?vid=catalog">Удалить</a>
                           <a href="/ADM/edit/' . $item_info['id'] . '/?vid=catalog'.'">Изменить</a>
                        ';
                        $image='<img src="/images/no_photo.jpg" width="286" alt="'.$item_info['title'].'" />';
                        if (file_exists(LocalDir.'/images/catalog/'.$item_info['id'].'---286.jpg')){
                            $image='<img src="/images/catalog/'.$item_info['id'].'---286.jpg" alt="'.$item_info['title'].'"/>';
                        }
                        echo '<div style="text-align:left;">'.kroshki('catalog', array('/'=>'Главная','/catalog.html'=>'Каталог','/catalog/item/'.$item_info['id']=>$item_info['title'])).'</div>';
                        ?>
                        <table width="100%">
                            <tr>
                                <td width="295">
                                    <h2>Артикул: <?=$item_info['art']?></h2>
                                    <div class="item-info-catalog-image">
                                        <?=$image?>
                                    </div>
                                    <table width="295" class="price-basket">
                                        <tr><td class="price-left"></td><td class="price"><?=$item_info['price']?> р.</td><td class="basket">
                                                <a class="addto-cart to-basket" href="/to_basket?item=<?=$item_info['id']?>">В корзину</a></td></tr>
                                    </table>
                                </td>
                                <td>
                                    <table class="item-info-head" width="100%"><tr><td class="tech">Тех. характеристики:</td>
                                            <td class="back-to-catalog"><a href="/catalog/">К списку всех товаров</a></td></tr></table>
                                    <div class="item-info-desc" style="height: 200px;"><?=$item_info['about']?></div>
                                </td>
                            </tr> 
                        </table>
                        <?
                        shadow_box(ob_get_clean());
                    }
                }
            break;
    }
    if ($target=='content'){
    ob_start();
    ?>
                            <script type="text/javascript">
                            
                                jQuery("a.to-basket").each(function(){
                                    jQuery(this).bind("click",function(){
                                        var urlTo=jQuery(this).attr("href");
                                        jQuery.post(urlTo , {d:1},function(data){                                            
                                                var bask=jQuery(".basket span");
                                                jQuery(bask).html(data);
                                                jQuery('.basket_window').dialog('open');
                                        }, "html");
                                        return false;
                                    });

                                });
                            </script>
    <?
    $text.=ob_get_clean();
    }
    echo $text;
}
function shadow_box($content){
    ?>
    <table class="item-info-catalog">
        <tr><td class="lt"></td><td class="tm"></td><td class="rt"></td></tr>
        <tr><td class="ll"></td><td class="item-info-catalog-content">
                <?=$content?>
            </td><td class="rr"></td></tr>
        <tr><td class="lb"></td><td class="bm"></td><td class="rb"></td></tr>
    </table>
    <?
}

?>
